package com.ruoyi.project.report.controller;

import com.alibaba.excel.write.handler.AbstractRowWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.ruoyi.project.domain.ReportTest;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DynamicMergeWriteHandler extends AbstractRowWriteHandler {
    private final List<ReportTest> dataList;

    public DynamicMergeWriteHandler(List<ReportTest> dataList) {
        this.dataList = dataList;
    }

    //    @Override
    public void afterRowDispose(WriteSheetHolder writeSheetHolder, Integer rowNum, Boolean isHead) {
        if (isHead) {
            return;
        }

        Map<String, Integer> mergeMap = new HashMap<>();
        Map<String, Integer> bigMergeMap = new HashMap<>();

        for (int i = 0; i < dataList.size(); i++) {
            ReportTest item = dataList.get(i);
            if (item.getMerge() != null) {
                mergeMap.put(item.getMerge(), mergeMap.getOrDefault(item.getMerge(), 0) + 1);
            }
            if (item.getBigMerge() != null) {
                bigMergeMap.put(item.getBigMerge(), bigMergeMap.getOrDefault(item.getBigMerge(), 0) + 1);
            }
        }

        for (Map.Entry<String, Integer> entry : mergeMap.entrySet()) {
            if (entry.getValue() > 1) {
                int firstRow = findFirstRowForMerge(entry.getKey(), dataList, "merge");
                writeSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(firstRow, firstRow + entry.getValue() - 1, 0, 0));
            }
        }

        for (Map.Entry<String, Integer> entry : bigMergeMap.entrySet()) {
            if (entry.getValue() > 1) {
                int firstRow = findFirstRowForMerge(entry.getKey(), dataList, "bigMerge");
                writeSheetHolder.getSheet().addMergedRegion(new CellRangeAddress(firstRow, firstRow + entry.getValue() - 1, 1, 1));
            }
        }
    }

    private int findFirstRowForMerge(String value, List<ReportTest> dataList, String property) {
        for (int i = 0; i < dataList.size(); i++) {
            ReportTest item = dataList.get(i);
            if (property.equals("merge") && value.equals(item.getMerge())) {
                return i + 1; // +1 因为行号从0开始
            } else if (property.equals("bigMerge") && value.equals(item.getBigMerge())) {
                return i + 1;
            }
        }
        return -1;
    }
}